package com.getpebble.android.framework.install.app;

import android.content.Context;
import android.net.Uri;
import com.getpebble.android.common.core.async.PblAsyncTask;
import com.getpebble.android.common.framework.install.app.AppBundle;
import com.getpebble.android.common.model.AppInfo;
import com.getpebble.android.common.model.FrameworkState;
import com.getpebble.android.framework.install.PebbleBundleManager;
import com.google.gson.JsonSyntaxException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.ZipFile;

public class AppBundleManager extends PebbleBundleManager<AppBundle> {
    public AppBundleManager(Context context) {
        super(context);
    }

    public String getDirectory() {
        return "apps";
    }

    public AppBundle getBundleFromFile(File file) throws IOException, JsonSyntaxException {
        if (file.exists()) {
            ZipFile zipFile = new ZipFile(file);
            return new AppBundle(zipFile, getComponents(zipFile));
        }
        throw new FileNotFoundException("Could not find " + file);
    }

    public void fetchAppInfoFromFile(final Uri uri, final FrameworkState frameworkState) {
        new PblAsyncTask() {
            public boolean doInBackground() {
                AppBundle appBundle = (AppBundle) AppBundleManager.this.fetchBundleFromUri(uri);
                AppInfo appInfo = null;
                if (appBundle != null) {
                    appInfo = appBundle.getAppInfo();
                }
                frameworkState.setAppInfo(appInfo);
                appBundle.closeFile();
                return true;
            }

            public void onTaskSuccess() {
            }

            public void onTaskFailed() {
            }
        }.submit();
    }
}
